<template>
	<view class="beforeOrder">
		<view class="unselAdd dFlex jBetween_aCenter" v-if='!address.id' @click='chooseAdd'>
			<view class='showDesc dFlex jStart_aCenter'>
				<u-icon name="plus-circle-fill" color='#1362C9'></u-icon>
				<text>添加收货地址</text>
			</view>
			<u-icon name="arrow-right"></u-icon>
		</view>
		<view class="selAdd dFlex jBetween_aCenter" v-if='address.id' @click='chooseAdd'>
			<view class="addInfo">
				<view class='add'>{{address.address+address.address_detail}}</view>
				<view class="user">{{address.receiver}} {{address.phone}}</view>
			</view>
			<u-icon name="arrow-right"></u-icon>
		</view>
		<view class="order">
			<view class="shops">
				<view class="shopOne dFlex jStart_aStart" v-for="(item,index) in shops" :key='index'>
					<view class="shopImg imgPublic">
						<image :src='item.main_img' mode='widthFix'></image>
					</view>
					<view class="shopInfo">
						<view class="shopName">{{item.name}}</view>
						<view class='config'>{{item.attribute.name}}</view>
						<view class="price dFlex jBetween_aCenter">
							<view class="showPrice">￥{{item.attribute.price}}</view>
							<view class="count">x{{item.num}}</view>
						</view>
					</view>
				</view>
			</view>
			<view class='line dFlex jBetween_aCenter'>
				<view class='lineTit'>优惠券</view>
				<view class="lineVal dFlex jEnd_aCenter">
					<text @click="chooseCoupon">{{coupon.id ? coupon.title + '减免'+ coupon.sub_price +'元' : '暂无相关优惠券'}}</text>
					<u-icon name="close-circle-fill" v-if='coupon.id' @click='coupon = {};getFreightInfo();'></u-icon>
					<u-icon name="arrow-right" v-else></u-icon>
				</view>
			</view>
			<view class='line dFlex jBetween_aCenter' style="border: none;">
				<view class='lineTit'>运费</view>
				<view class="lineVal dFlex jEnd_aCenter">
					<text style="color:#FF0000;font-size:12px;" v-if='showFreight <= 0'>包邮</text>
					<text style="color:#FF0000;font-size:12px;" v-else>{{showFreight}}元，满{{conditionFreight}}免运费</text>
					<!-- <u-icon name="arrow-right"></u-icon> -->
				</view>
			</view>
			<view class='line dFlex jBetween_aCenter' style="border: none;">
				<view class='lineTit'></view>
				<view class="lineVal dFlex jEnd_aCenter">
					<text style="color:#333">共{{allCount?allCount:0}}件</text>
					<text style="color:#333;margin-left:12px;">小计：￥</text>
					<text style="color:#FF0000;font-size:16px;">{{orderPrice?orderPrice:'0.00'}}</text>
					<!-- <u-icon name="arrow-right"></u-icon> -->
				</view>
			</view>
		</view>
		<view class="bottomInfo dFlex jEnd_aCenter">
			<view class="total">合计：￥<text>{{allPrice?allPrice:'0.00'}}</text></view>
			<view class="payBtn" @click="createOrder">付 款</view>
		</view>
	</view>
</template>

<script>
	import {
		getGoodsDetail,shipInfo,getAddressList,createOrderByGoodsid,orderPay,
		cartGoodsList,createOrderByCartgoods
	} from '@/tools/http.js';
	export default {
		data() {
			return {
				status:'',	//1 单商品购买 2购物车购买
				// 直接购买
				goodId:'',	// 单商品 商品id
				goodsAttrId:'',	// 单商品 选择的规格
				num:'',			//单商品 购买数量
				
				// 购物车结算
				ids:'',
				
				address:{},
				coupon:{},
				
				shops:[],	//商品信息
				oldPrice:'',
				orderPrice:0, //显示的总价格
				showFreight:0,//显示用运费
				freight:0,   //计算用运费
				conditionFreight:0,	//满多少减运费
				allPrice:0,	//综合费用
				allCount:0, //商品总数量
			};
		},
		onLoad(e){
			this.status = e.status;
			if(this.status == '1'){
				this.goodId = e.id;
				this.goodsAttrId = e.goodsAttrId;
				this.num = e.num;
				this.getShopInfo();
			}else if(this.status == '2'){
				this.ids = e.ids.split(',');
				this.getCarShop();
			}
			// 收货地址
			this.getAddressList();
		},
		onShow(){
			if(this.coupon.id){
				this.calcPrice();
			}
		},
		methods:{
			// 创建订单支付
			async createOrder(){
				if(!this.address.id){
					uni.showToast({
						title:'请选择收货地址',
						icon:"none"
					})
					return;
				}
				uni.showActionSheet({
					itemList:['微信支付','余额支付'],
					success: async (op) => {
						let orderData = {
							address_id:this.address.id,
							coupon:this.coupon.id?this.coupon.id:'',
							paytype:op.tapIndex == '0'?'wxpay':'balance',
						}
						if(this.status == '1'){ //单商品购买
							orderData.goods_id = this.goodId;
							orderData.goods_attr_id = this.goodsAttrId;
							orderData.num = this.num;
							let res = await createOrderByGoodsid(orderData);
							if(res){ 
								let payInfo = await orderPay({
									oid:res.id,
								});
								if(payInfo){
									if(op.tapIndex == '0'){
										uni.requestPayment({
											provider:'wxpay',
											timeStamp:payInfo.info.timeStamp,
											nonceStr:payInfo.info.nonceStr,
											package:payInfo.info.package,
											signType:payInfo.info.signType,
											paySign:payInfo.info.paySign,
											success: () => {
												uni.showToast({
													title:'成功创建订单',
													icon:"success"
												})
												setTimeout(()=>{
													uni.navigateBack({
														delta:1
													})
												},1650)
											},
											fail:(err)=>{
												console.log(err);
												uni.showToast({
													title:'订单支付失败',
													icon:"none"
												})
												setTimeout(()=>{
													uni.redirectTo({
														url:'/person/orders?status=0'
													})
												},1650)
											}
										})
									}else{
										uni.showToast({
											title:'成功创建订单',
											icon:"success"
										})
										setTimeout(()=>{
											uni.navigateBack({
												delta:1
											})
										},1650)
									}
								}
							}
						}else if(this.status == '2'){
							orderData.ids = this.ids.join(',');
							let res = await createOrderByCartgoods(orderData);
							if(res){ 
								let payInfo = await orderPay({
									oid:res.id,
								});
								if(payInfo){
									if(op.tapIndex == '0'){
										uni.requestPayment({
											provider:'wxpay',
											timeStamp:payInfo.info.timeStamp,
											nonceStr:payInfo.info.nonceStr,
											package:payInfo.info.package,
											signType:payInfo.info.signType,
											paySign:payInfo.info.paySign,
											success: () => {
												uni.showToast({
													title:'成功创建订单',
													icon:"success"
												})
												setTimeout(()=>{
													uni.navigateBack({
														delta:1
													})
												},1650)
											},
											fail:(err)=>{
												console.log(err);
												uni.showToast({
													title:'订单支付失败',
													icon:"none"
												})
												setTimeout(()=>{
													uni.redirectTo({
														url:'/person/orders?status=0'
													})
												},1650)
											}
										})
									}else{
										uni.showToast({
											title:'成功创建订单',
											icon:"success"
										})
										setTimeout(()=>{
											uni.navigateBack({
												delta:1
											})
										},1650)
									}
								}
							}
						}
					},
					fail:(err)=>{
						console.log(err);
					}
				})
			},
			// 获取购物车商品
			async getCarShop(){
				let res = await cartGoodsList({});
				if(res && res.length){
					this.ids.forEach((item)=>{
						let shopOne = res.find((shop)=>{
							return shop.id == item;
						});
						if(shopOne.id){
							let shopData = {
								main_img:shopOne.main_img,
								name:shopOne.goods_title,
								num:shopOne.num,
							}
							if(shopOne.goods_attr_id){
								shopData.attribute = {name:shopOne.attr_name,price:shopOne.price};
							}else{
								shopData.attribute = {name:'默认规则',price:shopOne.price};
							}
							this.shops.push(shopData);
						}
					})
					// 运费信息
					this.getFreightInfo();
				}
			},
			// 收货地址列表
			async getAddressList(){
				let res = await getAddressList({});
				if(res && res.length){
					this.address = res.find((item)=>{
						return item.is_default == '1'
					}).id ? res.find((item)=>{
						return item.is_default == '1'
					}) : {};
				}
			},
			// 选择收货地址
			chooseAdd(){
				uni.navigateTo({
					url:'/person/address'
				})
			},
			// 运费信息
			async getFreightInfo(){
				let res = await shipInfo({});
				if(res){
					this.freight = res.ship_money;
					this.showFreight = res.ship_money;
					this.conditionFreight = res.free_ship_money;
					this.calcPrice();
				}
			},
			// 单商品 商品详情
			async getShopInfo(){
				let res = await getGoodsDetail({
					id:this.goodId,
				});
				if(res){
					if(this.goodsAttrId){
						this.shops.push({
							main_img:res.main_img,
							name:res.title,
							attribute:res.attribute_list.find((item)=>{return item.id == this.goodsAttrId}),
							num:this.num,
						})
					}else{
						this.shops.push({
							main_img:res.main_img,
							name:res.title,
							attribute:{name:'默认规则',price:res.price},
							num:this.num,
						})
					}
					// 运费信息
					this.getFreightInfo();
				}
			},
			// 选择优惠券
			chooseCoupon(){
				uni.navigateTo({
					url:'./coupon?orderPrice='+this.oldPrice
				})
			},
			// 计算商品价格和总支付金额
			calcPrice(){
				this.orderPrice = 0;
				this.allCount = 0;
				this.shops.forEach((item,index)=>{
					let priceOne = item.num * item.attribute.price;
					this.allCount = this.allCount + parseInt(item.num);
					this.orderPrice = parseFloat(priceOne) + this.orderPrice;
				})
				this.oldPrice = this.orderPrice;
				if(this.freight > 0){ //需要运费
					// 存在优惠券时 先计算优惠之后的价格再判断是否免运费 
					if(this.coupon.id){
						// 0无门槛 1满减 4折扣券
						if(this.coupon.type == '0'){
							this.orderPrice = parseFloat(this.oldPrice) - parseFloat(this.coupon.sub_price);
						}else if(this.coupon.type == '1'){
							this.orderPrice = parseFloat(this.oldPrice) - parseFloat(this.coupon.sub_price);
						}else if(this.coupon.type == '4'){
							this.coupon.sub_price = this.oldPrice * (this.coupon.discount / 10);
							if(parseFloat(this.coupon.sub_price) > parseFloat(this.coupon.discount_limit)){
								this.coupon.sub_price = this.coupon.discount_limit;
								this.orderPrice = this.oldPrice - parseFloat(this.coupon.discount_limit);
							}else{
								this.orderPrice = this.oldPrice * (this.coupon.discount / 10);
							}
						}
					}
					this.orderPrice = this.orderPrice < 0 ? 0 : this.orderPrice;
					if(this.orderPrice >= this.conditionFreight){
						this.freight = 0;
					}
					this.allPrice = parseFloat(this.orderPrice) + parseFloat(this.freight);
				}else{ //不需要运费
					this.allPrice = this.orderPrice;
				}
			},
		}
	}
</script>

<style lang="scss">
	.beforeOrder{
		width:100%;
		padding:12px;
		box-sizing:border-box;
		.bottomInfo{
			width:100%;
			background:white;
			padding:12px;
			box-sizing: border-box;
			position: fixed;
			left: 0;
			bottom: 0;
			font-size: 13px;
			.total{
				text{
					color:#FF0606;
					font-size:16px;
					font-weight: bold;
				}
			}
			.payBtn{
				width:max-content;
				color:white;
				border-radius: 50px;
				padding: 5px 20px;
				background:#1362C9;
				font-size:12px;
				margin-left: 12px;
			}
		}
		.order{
			width:100%;
			background:white;
			border-radius:6px;
			margin-top:12px;
			padding:12px;
			box-sizing: border-box;
			.line{
				width:100%;
				padding:12px 0;
				box-sizing:border-box;
				border-bottom:1px solid #E6E6E6;
				.lineVal{
					flex:1;
					margin-left:12px;
					text{
						font-size:12px;
						color:#808080;
						display:inline-block;
						margin-right:5px;
					}
				}
				.lineTit{
					font-size:13px;
					font-weight:bold;
				}
			}
			.shops{
				width:100%;
				border-bottom:1px solid #E6E6E6;
				.shopOne{
					width:100%;
					margin-bottom:12px;
					.shopImg{
						width:65px;
						max-height:65px;
						image{
							width:100%;
							display:inline-block;
							border-radius:6px;
						}
					}
					.shopInfo{
						width:calc(100% - 77px);
						margin-left: 12px;
						.price{
							width:100%;
							font-size:12px;
							.showPrice{
								color:#FF0606;
							}
							.count{
								color:#808080;
								font-size:10px;
							}
						}
						.config{
							width:100%;
							font-size:12px;
							margin:5px auto 20px;
							color:#808080;
						}
						.shopName{
							width:100%;
							overflow:hidden;
							text-overflow: ellipsis;
							white-space:nowrap;
							font-size:16px;
							font-weight:bold;
						}
					}
				}
			}
		}
		.selAdd{
			width:100%;
			padding:12px;
			box-sizing:border-box;
			background:white;
			border-radius:6px;
			.addInfo{
				flex:1;
				.add{
					font-weight:bold;
					margin-bottom:8px;
				}
			}
		}
		.unselAdd{
			width:100%;
			padding:12px;
			box-sizing:border-box;
			background:white;
			border-radius:6px;
			text{
				display: inline-block;
				margin-left:8px;
			}
		}
	}
</style>
